@using System.IO
@using Microsoft.AspNetCore.Components.Web.Media
@implements IAsyncDisposable

<h3>Image Component Tests</h3>

<div>
    <h4>Test Controls</h4>
    <button id="load-png" @onclick="ReloadPng">Load PNG</button>
    <button id="load-jpg-stream" @onclick="LoadJpgFromStream">Load JPG (Stream)</button>
    <button id="change-source" @onclick="ChangeDynamicImageSource">Change Dynamic Source</button>
    <button id="load-pair-sequence" @onclick="LoadPairSequence">Load Two Images (Same Key)</button>
    <button id="load-error" @onclick="LoadErrorImage">Load Error</button>
    <button id="load-cached-jpg" @onclick="LoadCachedJpg">Load Cached JPG</button>
    <button id="load-invalid-mime" @onclick="LoadInvalidMimeImage">Load Invalid MIME</button>
    <button id="load-templated-image" @onclick="LoadTemplatedImage">Load Templated Image</button>

    <div id="test-status">
        Status: <span id="current-status">@_currentStatus</span>
    </div>
</div>

@if (_pngBasic)
{
    <h4>PNG basic</h4>
    <Image @ref="@_pngBasicRef" id="png-basic" Source="@_basicImageSource" />
}
@if (_jpgStream)
{
    <h4>JPG Stream</h4>
    <Image @ref="@_jpgStreamRef" id="jpg-stream" Source="@_jpgStreamSource" />
}
@if (_dynamicSource)
{
    <h4>Dynamic Source Image</h4>
    <Image @ref="@_dynamicSourceRef" id="dynamic-source" Source="@_dynamicImageSource" />
}
@if (_pair1Visible)
{
    <h4>Pair Image 1</h4>
    <Image @ref="@_pair1Ref" id="pair-image-1" Source="@_pairSource" />
}
@if (_pair2Visible)
{
    <h4>Pair Image 2</h4>
    <Image @ref="@_pair2Ref" id="pair-image-2" Source="@_pairSource" />
}
@if (_errorImage)
{
    <h4>Error Image</h4>
    <Image @ref="_errorRef" id="error-image" Source="@_errorSource" />
}
@if (_cachedJpgVisible)
{
    <h4>Cached JPG</h4>
    <Image @ref="@_cachedJpgRef" id="cached-jpg" Source="@_cachedJpgSource" />
}
@if (_invalidMimeImage)
{
    <h4>Invalid MIME Image</h4>
    <Image @ref="@_invalidMimeRef" id="invalid-mime-image" Source="@_invalidMimeSource" />
}
@if (_templatedImageVisible)
{
    <h4>Templated Image</h4>
    <Image @ref="_templatedImageComponent" Source="@_templatedImageSource" Context="ctx">
        <figure id="templated-image-wrapper" class="templated-image @(ctx.IsLoading ? "loading" : ctx.HasError ? "error" : "ready")">
            @if (ctx.ObjectUrl is not null)
            {
                <img id="templated-image" @ref="ctx.Element" data-blazor-image src="@ctx.ObjectUrl" />
            }
            else
            {
                <img id="templated-image" @ref="ctx.Element" data-blazor-image />
            }
            <figcaption id="templated-image-status">
                @(ctx.IsLoading ? "Loading..." : ctx.HasError ? "Error" : ctx.ObjectUrl is not null ? "Loaded" : "Idle")
            </figcaption>
        </figure>
    </Image>
}

@code {
    private Image _pngBasicRef;
    private Image _jpgStreamRef;
    private Image _dynamicSourceRef;
    private Image _pair1Ref;
    private Image _pair2Ref;
    private Image _errorRef;
    private Image _cachedJpgRef;
    private Image _invalidMimeRef;
    private Image _templatedImageComponent;

    private MediaSource _basicImageSource = new MediaSource(new byte[0], string.Empty, string.Empty);
    private MediaSource _jpgStreamSource = new MediaSource(new byte[0], string.Empty, string.Empty);
    private MediaSource _dynamicImageSource = new MediaSource(new byte[0], string.Empty, string.Empty);
    private MediaSource _pairSource = new MediaSource(new byte[0], string.Empty, string.Empty);
    private MediaSource _errorSource = new MediaSource(new byte[0], string.Empty, string.Empty);
    private MediaSource _cachedJpgSource = new MediaSource(new byte[0], string.Empty, string.Empty);
    private MediaSource _invalidMimeSource = new MediaSource(new byte[0], string.Empty, string.Empty);
    private MediaSource _templatedImageSource = new MediaSource(new byte[0], string.Empty, string.Empty);

    private bool _pngBasic;
    private bool _jpgStream;
    private bool _dynamicSource;
    private bool _pair1Visible;
    private bool _pair2Visible;
    private bool _errorImage;
    private bool _cachedJpgVisible;
    private bool _invalidMimeImage;
    private bool _templatedImageVisible;

    private string _currentStatus = "Ready";
    private bool _isCurrentlyShowingPng = true;

    private static readonly byte[] TestPngData = Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAA1JREFUGFdjqK6u/g8ABVcCcYoGhmwAAAAASUVORK5CYII=");
    private static readonly byte[] TestJpgData = Convert.FromBase64String("/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/wAALCAABAAEBAREA/8QAFAABAAAAAAAAAAAAAAAAAAAAAP/EABQQAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQEAAD8AN//Z");

    private void ReloadPng()
    {
        _basicImageSource = new MediaSource(TestPngData, "image/png", "test-png-basic");
        _pngBasic = true;
        _currentStatus = "PNG basic loaded";
    }

    private void LoadJpgFromStream()
    {
        _currentStatus = "Loading JPG from stream...";
        var stream = new MemoryStream(TestJpgData);
        _jpgStreamSource = new MediaSource(stream, "image/jpeg", "test-jpg-stream");
        _jpgStream = true;
        _currentStatus = "JPG from stream loaded";
    }

    private void ChangeDynamicImageSource()
    {
        if (!_dynamicSource)
        {
            _currentStatus = "Dynamic source initialized with PNG";
            _dynamicImageSource = new MediaSource(TestPngData, "image/png", "dynamic-png");
            _dynamicSource = true;
            _isCurrentlyShowingPng = true;
        }
        else
        {
            if (_isCurrentlyShowingPng)
            {
                _currentStatus = "Dynamic source changed to JPG";
                _dynamicImageSource = new MediaSource(TestJpgData, "image/jpeg", "dynamic-jpg");
            }
            else
            {
                _currentStatus = "Dynamic source changed to PNG";
                _dynamicImageSource = new MediaSource(TestPngData, "image/png", "dynamic-png");
            }
            _isCurrentlyShowingPng = !_isCurrentlyShowingPng;
        }
    }

    private void LoadPairSequence()
    {
        _currentStatus = "Loading pair sequence...";
        _pairSource = new MediaSource(TestJpgData, "image/jpeg", "pair-cache");
        _pair1Visible = true;
        _pair2Visible = true;
        _currentStatus = "Pair second loaded";
    }

    private void LoadErrorImage()
    {
        _currentStatus = "Loading error image...";
        var ms = new MemoryStream(new byte[] { 1, 2, 3, 4 });
        ms.Seek(ms.Length, SeekOrigin.Begin);
        _errorSource = new MediaSource(ms, "image/png", "error-key");
        _errorImage = true;
        _currentStatus = "Error image loaded";
    }

    private void LoadCachedJpg()
    {
        _currentStatus = "Loading cached JPG...";
        _cachedJpgSource = new MediaSource(TestJpgData, "image/jpeg", "single-cached-jpg");
        _cachedJpgVisible = true;
        _currentStatus = "Cached JPG loaded";
    }

    private void LoadInvalidMimeImage()
    {
        _currentStatus = "Loading invalid mime image...";
        var bytes = new byte[] { 97 }; // 'a'
        _invalidMimeSource = new MediaSource(bytes, "text/plain", Guid.NewGuid().ToString());
        _invalidMimeImage = true;
        _currentStatus = "Invalid mime image loaded";
    }

    private void LoadTemplatedImage()
    {
        _currentStatus = "Loading templated image...";
        _templatedImageSource = new MediaSource(TestPngData, "image/png", "templated-png");
        _templatedImageVisible = true;
        _currentStatus = "Templated image loaded";
    }

    public async ValueTask DisposeAsync()
    {
        if (_dynamicSourceRef != null) await _dynamicSourceRef.DisposeAsync();
        if (_jpgStreamRef != null) await _jpgStreamRef.DisposeAsync();
        if (_pngBasicRef != null) await _pngBasicRef.DisposeAsync();
        if (_pair1Ref != null) await _pair1Ref.DisposeAsync();
        if (_pair2Ref != null) await _pair2Ref.DisposeAsync();
        if (_invalidMimeRef != null) await _invalidMimeRef.DisposeAsync();
    if (_templatedImageComponent != null) await _templatedImageComponent.DisposeAsync();
    }
}
